package com.general.framework.mp;

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapDemo {
    public static void main(String[] args) {
        // 创建一个 LinkedHashMap，保持插入顺序
        LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();

        // 插入元素
        linkedHashMap.put(3, "Three");
        linkedHashMap.put(1, "One");
        linkedHashMap.put(2, "Two");

        // 遍历 LinkedHashMap，按照插入顺序
        for (Map.Entry<Integer, String> entry : linkedHashMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // 创建一个 LinkedHashMap，按照访问顺序
        LinkedHashMap<Integer, String> accessOrderMap = new LinkedHashMap<>(16, 0.75f, true);
        accessOrderMap.put(3, "Three");
        accessOrderMap.put(1, "One");
        accessOrderMap.put(2, "Two");

        // 访问元素
        accessOrderMap.get(1);
        accessOrderMap.get(3);

        // 遍历 LinkedHashMap，按照访问顺序
        for (Map.Entry<Integer, String> entry : accessOrderMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
        // 最近最常访问的元素排在链表末尾
        System.out.println(accessOrderMap);
    }
}
